package io.renren.modules.secretary.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.annotation.SysLog;
import io.renren.common.utils.Constant;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.common.entity.Teacher;
import io.renren.modules.generator.entity.ClassEntity;
import io.renren.modules.generator.service.ClassService;
import io.renren.modules.secretary.service.HeadMasterService;
import io.renren.modules.secretary.service.TeacherService;
import io.renren.modules.sys.entity.SysRoleEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.entity.SysUserRoleEntity;
import io.renren.modules.sys.service.SysRoleService;
import io.renren.modules.sys.service.SysUserRoleService;
import io.renren.modules.sys.service.SysUserService;
import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static io.renren.common.utils.ShiroUtils.getUserId;

/**
 * @author wks
 * @date 2022/2/7 16:21
 */
@RestController
@RequestMapping("/secretary/headmaster")
public class HeadMasterController {

    @Autowired
    HeadMasterService headMasterService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private ClassService classService;

    @Autowired
    private SysUserService sysUserService;

    /**
     * 所有班主任列表
     */
    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        Page<Map<String, Object>> page = new Page<>( Long.valueOf(String.valueOf(params.get("page"))),  Long.valueOf(String.valueOf(params.get("limit"))));
        IPage<Map<String, Object>> mapIPage = headMasterService.selectStudentList(page, params);
        PageUtils newPage = new PageUtils(mapIPage);

        return R.ok().put("page", newPage);
    }

    /**
     * 班主任角色列表
     */
    @GetMapping("/select")
    public R select() {
        Map<String, Object> map = new HashMap<>();

        //如果不是超级管理员，则只查询自己所拥有的角色列表
//        if (getUserId() != Constant.SUPER_ADMIN) {
//            map.put("create_user_id", getUserId());
//        }
        map.put("role_id", 2);
        List<SysRoleEntity> list = (List<SysRoleEntity>) sysRoleService.listByMap(map);

        return R.ok().put("list", list);
    }

    /**
     * 新增班主任
     */
    @SysLog("新增班主任")
    @PostMapping("/save")
    public R save(@RequestBody Teacher teacher) {
        SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
        SysUserEntity sysUserEntity = new SysUserEntity();
        sysUserEntity.setUserId(teacher.getUserId());
        sysUserEntity.setClassId(teacher.getClassId());
        sysUserService.updateById(sysUserEntity);
        sysUserRoleEntity.setRoleId(teacher.getRoleIdList().get(0));
        sysUserRoleEntity.setUserId(teacher.getUserId());
        sysUserRoleService.save(sysUserRoleEntity);
        ClassEntity classEntity = new ClassEntity();
        classEntity.setClassId(teacher.getClassId());
        classEntity.setTeacherId(teacher.getUserId());
        classService.updateById(classEntity);
        return R.ok();
    }

    /**
     * 修改班主任
     */
    @SysLog("修改班主任")
    @PostMapping("/update")
    @Transactional
    public R update(@RequestBody Teacher teacher) {
        //删除以前角色表的数据
        ClassEntity classEntity = classService.getById(teacher.getClassId());
        Long teacherId = classEntity.getTeacherId();
        QueryWrapper<SysUserRoleEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", teacherId).eq("role_id", 2L);
        SysUserRoleEntity sysUserRole = sysUserRoleService.getOne(wrapper);
        sysUserRoleService.removeById(sysUserRole.getId());
        //新增新的角色表数据
        SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
        //设置为班主任角色id
        sysUserRoleEntity.setRoleId(2L);
        sysUserRoleEntity.setUserId(teacher.getUserId());
        sysUserRoleService.save(sysUserRoleEntity);
        ClassEntity classEntity1 = new ClassEntity();
        classEntity1.setClassId(teacher.getClassId());
        classEntity1.setTeacherId(teacher.getUserId());
        classService.updateById(classEntity1);
        SysUserEntity sysUserEntity = new SysUserEntity();
        sysUserEntity.setUserId(teacher.getUserId());
        sysUserEntity.setClassId(teacher.getClassId());
        sysUserService.update(sysUserEntity);
        return R.ok();
    }

    /**
     * 删除班主任
     */
    @SysLog("删除班主任")
    @PostMapping("/delete")
    public R delete(@RequestBody Long[] userIds) {
        if (ArrayUtils.contains(userIds, 1L)) {
            return R.error("系统管理员不能删除");
        }

        if (ArrayUtils.contains(userIds, getUserId())) {
            return R.error("当前用户不能删除");
        }
        List<Long> sysRoles = new ArrayList<>();
        for (int index = 0; index < userIds.length; index++) {
            QueryWrapper<SysUserRoleEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userIds[index]).eq("role_id", 2L);
            SysUserRoleEntity sysUserRole = sysUserRoleService.getOne(wrapper);
            sysRoles.add(sysUserRole.getId());
            QueryWrapper<ClassEntity> classWrapper = new QueryWrapper<>();
            classWrapper.eq("teacher_id", userIds[index]);
            ClassEntity classEntity = classService.getOne(classWrapper);
            classService.deleteTeacherId(classEntity.getClassId());
        }
        sysUserRoleService.removeByIds(sysRoles);


        return R.ok();
    }

}
